#include "dialog.h"

Dialog::Dialog(QString message, QList<QString> buttonNames, QPixmap background, QWidget* parent) :
        QWidget(parent),
        layout(this),
        messageLabel(message, this),
        backgroundPixmap(background),
        signalMapper(this)
{
    // Create the buttons and signal mappings
    for(int i = 0; i < buttonNames.length(); i++)
    {
        buttonsList.append(new QPushButton(buttonNames[i], this));
        connect(buttonsList[i], SIGNAL(clicked()), &signalMapper, SLOT(map()));
        signalMapper.setMapping(buttonsList[i], i);
    }

    // Setup the buttonClicked signal
    connect(&signalMapper, SIGNAL(mapped(int)), this, SIGNAL(buttonClicked(int)));

    // Add the buttons to the layout and set their sytles
    QPushButton* currentButton;
    foreach (currentButton, buttonsList)
    {
        currentButton->setStyleSheet("font-family: Arial, Helvetica, sans-serif;"
                                     "font-size: 36px;"
                                     "font-weight: bold;");
        layout.addWidget(currentButton, 1, buttonsList.indexOf(currentButton));
    }

    // Add the message to the layout and set its style
    messageLabel.setStyleSheet("font-family: Arial, Helvetica, sans-serif;"
                               "font-size: 24px;");
    messageLabel.setWordWrap(true);
    layout.addWidget(&messageLabel, 0, 0, 1, layout.columnCount(), Qt::AlignCenter);

    // Make the widget the size of the background image
    this->resize(backgroundPixmap.size());

    // Hide the dialog until showDialog() is called
    this->setVisible(false);
}

void Dialog::paintEvent(QPaintEvent *event)
{
    // Paint the background
    QPainter painter(this);
    painter.drawPixmap(0, 0, backgroundPixmap);
    painter.end();
}

void Dialog::showDialog()
{
    this->setVisible(true);

    // Animate the dialog flying in from the left
    QPropertyAnimation* animation = new QPropertyAnimation(this, "pos", this);
    animation->setDuration(500);
    animation->setStartValue(QPoint(-this->width(), this->pos().y()));
    animation->setEndValue(this->pos());
    animation->setEasingCurve(QEasingCurve::OutSine);
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void Dialog::hideDialog()
{
    // Animate the dialog flying out to the right
    QPropertyAnimation* animation = new QPropertyAnimation(this, "pos", this);
    animation->setDuration(500);
    animation->setStartValue(this->pos());
    animation->setEndValue(QPoint(
            QApplication::desktop()->screenGeometry().width(),
            this->pos().y()));
    animation->setEasingCurve(QEasingCurve::InSine);

    // Hide the dialog when the animation finishes
    connect(animation, SIGNAL(finished()), SLOT(hide()));

    animation->start(QAbstractAnimation::DeleteWhenStopped);
}
